<template>
<div>
  <div>
    <el-select v-model="searchValues.dsAreaId">
      <el-option :value="item.dsAreaId" label="全部"></el-option>
      <el-option v-for="one in areas" :value="one.dsAreaId" :key="one.dsAreaId" :label="one.dsAreaName"></el-option>
    </el-select>
    <el-select v-model="searchValues.dsTypeId">
      <el-option :value="item.dsTypeId" label="全部"></el-option>
      <el-option v-for="one in types" :value="one.dsTypeId" :key="one.dsTypeId" :label="one.dsTypeName"></el-option>
    </el-select>
    <el-select v-model="searchValues.dsDeviceRunStatus">
      <el-option :value="item.dsDeviceRunStatus" label="全部"></el-option>
      <el-option v-for="one in dsDeviceRunStatusByNameAndId" :value="one.dsDeviceRunStatusId"
                 :key="one.dsDeviceRunStatusId" :label="one.dsDeviceRunStatusName"></el-option>
    </el-select>
    <el-input style="width: 200px" v-model="searchValues.dsDeviceMac"/>

    <el-button class="ml-15" type="primary" @click="searchDeviceBySearchValues()">搜索</el-button>
    <el-button class="ml-15" type="success" @click="searchDeviceBySearchValuesAll()">显示全部</el-button>

  </div>
  <el-dialog :title="formTitle" :visible.sync="dialogFormVisible" width="500px">
    <el-form :model="form">
      <el-form-item label="设备型号" :label-width="formLabelWidth">
        <el-input v-model='form.dsDeviceModel' placeholder="如：esp32" style="width: 200px" disabled></el-input>
      </el-form-item>
      <el-form-item label="安装位置" :label-width="formLabelWidth">
        <el-input v-model='form.dsDeviceAddr' placeholder="如：前门" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="所属场所" :label-width="formLabelWidth">
        <el-select v-model="form.dsAreaId" placeholder="--请选择场所--">
          <el-option v-for="one in areas" :value="one.dsAreaId" :key="one.dsAreaId" :label="one.dsAreaName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="MAC地址" :label-width="formLabelWidth">
        <el-input v-model="form.dsDeviceMac" placeholder="如：48-E7-DA-54-EE-AF" disabled></el-input>
      </el-form-item>
      <el-form-item label="固件版本" :label-width="formLabelWidth">
        <el-input v-model="form.dsDeviceFirmware" placeholder="如：" style="width: 200px" disabled></el-input>
      </el-form-item>
      <el-form-item label="设备类型" :label-width="formLabelWidth">
        <el-select v-model="form.dsTypeId" placeholder="--请选择设备类型--" multiple>
          <el-option v-for="one in types" :value="one.dsTypeId" :key="one.dsTypeId" :label="one.dsTypeName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" :label-width="formLabelWidth" >
        <el-input v-model="form.dsDeviceStatus" placeholder="如：" style="width: 200px"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="editHandler()">确 定</el-button>
    </div>
  </el-dialog>
  <div style="margin: 10px 0"  >
    <el-button type="primary" @click="add()">添加设备<i class="el-icon-circle-plus-outline"></i></el-button>
  <el-button type="danger" @click="removeAll()">批量删除<i class="el-icon-remove-outline"></i></el-button>

  </div>
  <el-table
      :data="tableData"
      ref="multipleTable"
      border
      style="width: 100%">
    <el-table-column
        type="selection" v-if="true">
    </el-table-column>
    <el-table-column
        label="安装位置"
        prop="dsDeviceAddr">
    </el-table-column>
    <el-table-column
        label="Mac地址"
        prop="dsDeviceMac">
    </el-table-column>
    <el-table-column
        label="设备型号"
        prop="dsDeviceModel">
    </el-table-column>
    <el-table-column
        label="传感器">
      <template slot-scope="scope">
        {{ itypes(scope.row) }}
      </template>
    </el-table-column>
    <el-table-column
        label="设备版本"
        prop="dsDeviceFirmware">
    </el-table-column>
    <el-table-column
        label="场所">
      <template slot-scope="scope">
        {{ scope.row.dsAreaId.dsAreaName }}
      </template>
    </el-table-column>
    <el-table-column
        label="当前状态">
      <template slot-scope="scope">
        {{ scope.row.state }}
      </template>
    </el-table-column>
    <el-table-column label="禁用">
      <template slot-scope="scope">
        <el-switch
            @change="changeSwitch(scope.row)"
            :value="scope.row.dsDeviceDisable === 0 "
            active-color="#13ce66"
            inactive-color="#ff4949">
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button type="warning" @click="edit(scope.row)">编辑<i class="el-icon-edit"></i> </el-button>
        <el-button type="danger" @click="remove(scope.row)">删除 <i class="el-icon-remove-outline"></i></el-button>
            <el-button type="warning" @click="rebootDevice(scope.row)">重启<i class="el-icon-reboot"></i></el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageTotal">
  </el-pagination>
</div>
</template>

<script>
export default {
  name: "Updevice",

  data() {
    return {
      searchValues: {
        page: this.currentPage, //第几页
        pageSize: this.pageSize,  //每页多少条数据
        dsAreaId: null,
        dsTypeId: null,
        dsDeviceRunStatus: null,
        dsDeviceMac: null
      },
      dsDeviceRunStatusByNameAndId: [
        {
          dsDeviceRunStatusId: 1,
          dsDeviceRunStatusName: "上线"
        }, {
          dsDeviceRunStatusId: 2,
          dsDeviceRunStatusName: "待用"
        }, {
          dsDeviceRunStatusId: 3,
          dsDeviceRunStatusName: "掉线"
        }, {
          dsDeviceRunStatusId: 4,
          dsDeviceRunStatusName: "禁用"
        }, {
          dsDeviceRunStatusId: 5,
          dsDeviceRunStatusName: "休眠"
        },
      ],
      form: {
        dsDeviceModel:null,
        dsDeviceMac:null,
        dsDeviceAddr:null,
        dsDeviceDisable:null,
        dsDeviceFirmware:null,
        dsAreaId:{
          createTime: null,
          deleted: null,
          dsAreaId: null,
          dsAreaName: null,
          dsAreaNote: null,
          modifyTime: null
        },
        dsTypeId: null,
        createTime:null,
        modifyTime:null,
        deleted:null,
        dsDeviceId:null,
        dsDeviceStatus:null
      },
      item : {
        dsDeviceModel:null,
        dsDeviceMac:null,
        dsDeviceAddr:null,
        dsDeviceDisable:null,
        dsDeviceFirmware:null,
        dsAreaId:{
          createTime: null,
          deleted: null,
          dsAreaId: null,
          dsAreaName: null,
          dsAreaNote: null,
          modifyTime: null
        },
        dsTypeId: [this.type],
        createTime:null,
        modifyTime:null,
        deleted:null,
        dsDeviceId:null,
        dsDeviceStatus:null,
        state: null
      },
      tableData: [
         this.item
      ],
      area: {
        createTime: null,
        deleted: null,
        dsAreaId: null,
        dsAreaName: null,
        dsAreaNote: null,
        modifyTime: null
      },
      areas: [
        this.area
      ],
      type: {
        createTime: null,
        deleted: null,
        dsTypeId: null,
        dsTypeName: null,
        modifyTime: null
      },
      types: [
        this.type
      ],
      dialogFormVisible:false,
      formLabelWidth: '120px',
      formTitle:'新增',
      pageTotal: 0,
      currentPage: 1,
      pageSize:5,
      searchValue: '',
      activeName: 'role',
    }
  },

  methods:{
    rebootDevice(data) {
      let datas=data.dsDeviceMac
      this.api.deviceApi.rebootDevice(datas);
    },
    searchDeviceBySearchValues() {
      this.currentPage = 1
      if (this.searchValues!=null){
        this.searchValues.pageSize = this.pageSize
        this.searchValues.page = this.currentPage
        this.api.deviceApi.searchDeviceBySearchValues(this.searchValues).then(res=> {
          this.tableData=res[0]
          this.pageTotal=res[1]
        }).catch(error => {
          console.log(error)
        })
      }
    },
    searchDeviceBySearchValuesAll(){
      this.searchValues.pageSize = this.pageSize
      this.searchValues.page = this.currentPage
      this.searchValues.dsAreaId=null
      this.searchValues.dsTypeId=null
      this.searchValues.dsDeviceRunStatus=null
      this.searchValues.dsDeviceMac=null
      this.api.deviceApi.searchDeviceBySearchValues(this.searchValues).then(res=> {
        this.tableData=res[0]
        this.pageTotal=res[1]
      }).catch(error => {
        console.log(error)
      })
    },

    removeAll() {
      console.log(this.$refs.multipleTable.selection)
      let ids = [];
      this.$confirm('此操作将删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for (const i in this.$refs.multipleTable.selection) {
          ids.push(this.$refs.multipleTable.selection[i].dsDeviceId)
        }
        if(ids.length===0){
          this.$confirm('请选择删除对象！', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        }
        else {
          this.api.deviceApi.deleteAll(ids).then((res) => {
            if (res) {
              this.$notify({
                title: '成功',
                message: '有' + ids.length + '个设备删除成功',
                type: 'success'
              })
              this.selectCurrentPageDevice(this.currentPage, this.pageSize, this.searchValue)
            } else {
              this.$notify.error({
                title: '失败'
              })
            }
          }).catch(err => {
            console.log(err)
            this.$notify.error({
              title: '失败',
              message: '信息：' + err
            })
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });

    },
    add:function () {
      this.form = {
        dsDeviceModel: null,
        dsDeviceMac:null,
        dsDeviceAddr:null,
        dsDeviceDisable:null,
        dsDeviceFirmware:null,
        dsAreaId:null,
        dsTypeId:null,
        createTime:null,
        modifyTime:null,
        deleted:null,
        dsDeviceId:null,
        dsDeviceTopic:null
      }
      this.formTitle = '添加设备'
      this.dialogFormVisible = true
    },
    cancel() {
      this.selectCurrentPageDevice(this.currentPage, this.pageSize, this.searchValue)
      this.dialogFormVisible = false
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.selectCurrentPageDevice(this.currentPage, pageSize, this.searchValue)
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.selectCurrentPageDevice(currentPage, this.pageSize, this.searchValue)
    },
    selectCurrentPageDevice: function (page, pageSize, name) {
      this.api.deviceApi.selectDevicePage(page, pageSize, name).then((response)=>{
       this.tableData = response[0]
        console.log('up')
        console.log(this.tableData)
        console.log('up')
        this.pageTotal = response[1]
        console.log(this.pageTotal)
      }).catch((error)=>{
        this.tableData = error
      })
    },
    disableDevice:function (data) {
      data.dsAreaId = data.dsAreaId.dsAreaId
      let arr = []
      data.dsTypeId.forEach(type => {
        arr.push(type.dsTypeId)
      })
      data.dsTypeId = arr
      if (data.dsDeviceDisable === 0) {
        data.dsDeviceDisable = 1
      } else {
        data.dsDeviceDisable = 0
      }
      this.api.deviceApi.disableDevice(data)
          .then(()=>{
            this.$notify({
              title: '成功',
              message: '第' + data.dsDeviceId + '个设备修改成功',
              type: 'success'
            })
            this.selectCurrentPageDevice(this.currentPage, this.pageSize, this.searchValue)
          })
          .catch((error)=>{
            data.dsDeviceDisable = 0
            this.$notify.error({
              title: '失败',
              message: '信息：' + error
            })
          })
    },
    searchDeviceByName(name) {
      this.currentPage = 1
      this.selectCurrentPageDevice(this.currentPage, this.pageSize, this.searchValue)
    },
    deleteDevice: function (data) {
      this.api.deviceApi.deleteDevice(data)
          .then((res) => {
            if (res) {
              this.$notify({
                title: '成功',
                message: '第' + data.dsDeviceId + '个设备删除成功',
                type: 'success'
              })
              this.selectCurrentPageDevice(this.currentPage, this.pageSize, name)
            } else {
              this.$notify.error({
                title: '失败'
              })
            }
          })
          .catch(err => {
            console.log(err)
            this.$notify.error({
              title: '失败',
              message: '信息：' + err
            })
          })
    },
    remove: function (data) {
      data.dsAreaId = data.dsAreaId.dsAreaId
      let arr = []
      data.dsTypeId.forEach(type => {
        arr.push(type.dsTypeId)
      })
      data.dsTypeId = arr
      this.$confirm('此操作将删除设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteDevice(data)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    changeSwitch: function (data) {
      this.$confirm('此操作将修改设备当前状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.disableDevice(data)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
     edit:function (data) {
      this.item = data
      this.form = data
      let arr = []
      this.form.dsTypeId.forEach(item => {
        arr.push(item.dsTypeId)
      })
      this.form.dsAreaId = this.form.dsAreaId.dsAreaId
      this.form.dsTypeId = arr
      this.dialogFormVisible = true
      this.formTitle = '编辑设备'
    },
    editDevice:function (data) {
      this.api.deviceApi.updateDevice(data)
          .then(()=>{
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success'
            })
            this.selectCurrentPageDevice(this.currentPage, this.pageSize, this.searchValue)
          })
          .catch((error)=>{
            this.$notify.error({
              title: '失败',
              message: '信息：' + error
            })
            console.log(error)
          })
      this.dialogFormVisible = false
    },
    editHandler: function () {
      if (this.form.dsDeviceId == null) {
        this.addDevice(this.form)
      } else {
        this.editDevice(this.form)
      }
    },
    addDevice:function (data) {
      console.log(data)
      this.api.deviceApi.addDevice(data)
          .then(()=>{
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success'
            })
            this.selectCurrentPageDevice(this.currentPage, this.pageSize, this.searchValue)
          })
          .catch((error)=>{
            this.$notify.error({
              title: '失败',
              message: '信息：' + error
            })
            console.log(error)
          })
      this.dialogFormVisible = false
    },
    itypes(items) {
      let s = "";
      items.dsTypeId.forEach(type => {
        s += type.dsTypeName + " "
      })
      return s
    },
    initWebSocket: function () { // 建立连接
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = localStorage.getItem("user");
      var url = "ws://localhost:8081/websocket/"+userId;
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketonopen;
      this.websock.send = this.websocketsend;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    },
    // 连接成功后调用
    websocketonopen: function () {
      console.log("WebSocket连接成功");
    },
    // 发生错误时调用
    websocketonerror: function (e) {
      console.log("WebSocket连接发生错误");
    },
    // 给后端发消息时调用
    websocketsend: function (e) {
      console.log("WebSocket连接发生错误");
    },
    // 接收后端消息
    // vue 客户端根据返回的cmd类型处理不同的业务响应
    websocketonmessage: function (e) {
      let data = JSON.parse(e.data)
      this.tableData.forEach(item => {
        if (item.dsDeviceMac === data.dsDeviceMac) {
            item.state = data.dsHistoryValue
        }
      })
    },
    // 关闭连接时调用
    websocketclose: function (e) {
      console.log("connection closed (" + e.code + ")");
    }
  },
  mounted() {
    this.selectCurrentPageDevice(this.currentPage, this.pageSize, this.searchValue)
    this.api.areaApi.selectAreas()
        .then(res => {this.areas = res
        })
        .catch(error => {console.log(error)})
    this.api.typeApi.selectTypes()
        .then(res => {this.types = res
        })
        .catch(err => {console.log(err)})
    this.initWebSocket()
  },
  destroyed: function () { // 离开页面生命周期函数
    this.websocketclose();
  }
}
</script>
